package com.now.printer.ui.activity;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.now.printer.R;
import com.now.printer.privacy_policy.AppUtil;
import com.now.printer.privacy_policy.PrivacyDialog;
import com.now.printer.privacy_policy.SPUtil;
import com.zh.pocket.ads.splash.SplashAD;
import com.zh.pocket.ads.splash.SplashADListener;
import com.zh.pocket.http.bean.ADError;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//import com.amitshekhar.DebugDB;

/**
 * Created by xudong on 2021/5/13.
 */

public class SplashActivity extends Activity implements SplashADListener {

//    public int getLayoutId() {
//        return R.layout.activity_splash;
//    }

    private boolean isFirst = true;
    public boolean mDisrupt = false;
    private FrameLayout container;
    public static final String START_APP = "start_app";
    private boolean isStartApp = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        LogUtil.i(" see ip address : " + (BuildConfig.DEBUG ? DebugDB.getAddressLog() : ""));
//        if (isFirst) {
//            isFirst = false;
//            initPermission();
//        }
        super.onCreate(savedInstanceState);

        if (getIntent() != null && getIntent().hasExtra(START_APP)) {
            isStartApp = getIntent().getBooleanExtra(START_APP, true);
        }
        setContentView(getContentView());

        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

        check();

    }

    /**
     * 显示隐私政策或跳转到其他界面
     */
    private String SP_PRIVACY = "sp_privacy";
    private String SP_VERSION_CODE = "sp_version_code";
    private long currentVersionCode;
    private long versionCode;
    private boolean isCheckPrivacy = false;

    private void check() {

        //先判断是否显示了隐私政策
        currentVersionCode = AppUtil.getAppVersionCode(this);
        versionCode = (long) SPUtil.get(this, SP_VERSION_CODE, 0L);
        isCheckPrivacy = (boolean) SPUtil.get(this, SP_PRIVACY, false);

        if (!isCheckPrivacy || versionCode != currentVersionCode) {
            showPrivacy();
        } else {
            openNewActivity(MainActivity.class);
//            Toast.makeText(this, getString(R.string.confirmed), Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 显示用户协议和隐私政策
     */
    private void showPrivacy() {

        final PrivacyDialog dialog = new PrivacyDialog(this);
        TextView tv_privacy_tips = dialog.findViewById(R.id.tv_privacy_tips);
        TextView btn_exit = dialog.findViewById(R.id.btn_exit);
        TextView btn_enter = dialog.findViewById(R.id.btn_enter);
        dialog.show();

        String string = getResources().getString(R.string.privacy_tips);
        String key1 = getResources().getString(R.string.privacy_tips_key1);
        String key2 = getResources().getString(R.string.privacy_tips_key2);
        int index1 = string.indexOf(key1);
        int index2 = string.indexOf(key2);

        //需要显示的字串
        SpannableString spannedString = new SpannableString(string);
        //设置点击字体颜色
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.colorBlue));
        spannedString.setSpan(colorSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.colorBlue));
        spannedString.setSpan(colorSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置点击字体大小
        AbsoluteSizeSpan sizeSpan1 = new AbsoluteSizeSpan(18, true);
        spannedString.setSpan(sizeSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        AbsoluteSizeSpan sizeSpan2 = new AbsoluteSizeSpan(18, true);
        spannedString.setSpan(sizeSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置点击事件
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SplashActivity.this, TermsActivity.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                //点击事件去掉下划线
                ds.setUnderlineText(false);
            }
        };
        spannedString.setSpan(clickableSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SplashActivity.this, PrivacyPolicyActivity.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                //点击事件去掉下划线
                ds.setUnderlineText(false);
            }
        };
        spannedString.setSpan(clickableSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //设置点击后的颜色为透明，否则会一直出现高亮
        tv_privacy_tips.setHighlightColor(Color.TRANSPARENT);
        //开始响应点击事件
        tv_privacy_tips.setMovementMethod(LinkMovementMethod.getInstance());

        tv_privacy_tips.setText(spannedString);

        //设置弹框宽度占屏幕的80%
        WindowManager m = getWindowManager();
        Display defaultDisplay = m.getDefaultDisplay();
        final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (int) (defaultDisplay.getWidth() * 0.80);
        dialog.getWindow().setAttributes(params);

        btn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                SPUtil.put(SplashActivity.this, SP_VERSION_CODE, currentVersionCode);
                SPUtil.put(SplashActivity.this, SP_PRIVACY, false);
                finish();
            }
        });

        btn_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                SPUtil.put(SplashActivity.this, SP_VERSION_CODE, currentVersionCode);
                SPUtil.put(SplashActivity.this, SP_PRIVACY, true);

                Toast.makeText(SplashActivity.this, getString(R.string.confirmed), Toast.LENGTH_SHORT).show();

                // 如果targetSDKVersion >= 23，就要申请好权限。如果您的App没有适配到Android6.0（即targetSDKVersion < 23），那么只需要在这里直接调用fetchSplashAD接口。
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            checkAndRequestPermission();
                    initPermission();
                } else {
                    // 如果是Android6.0以下的机器，默认在安装时获得了所有权限，可以直接调用SDK
//            fetchSplashAD(this, container, this);
                    openNewActivity(MainActivity.class);

                }
            }
        });

    }

    /**
     * 获取需要适配 Android 6.0 之后的权限
     *
     * @return 返回需要适配的权限
     */
    public List<String> getNeedCheckPermissions() {
        return Arrays.asList(
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA
        );
    }

    private void initPermission() {
        XXPermissions.with(this)
                // 申请安装包权限
                //.permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 申请悬浮窗权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW)
                // 申请通知栏权限
                //.permission(Permission.NOTIFICATION_SERVICE)
                // 申请系统设置权限
                //.permission(Permission.WRITE_SETTINGS)
                // 申请单个权限
//                .permission(Permission.RECORD_AUDIO)
                // 申请多个限

                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
//                            toast("获取录音和日历权限成功");
                        } else {
//                            toast("获取部分权限成功，但部分权限未正常授予");
                        }
                        openNewActivity(MainActivity.class);
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
//                            toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(SplashActivity.this, permissions);
                        } else {
//                            toast("获取录音和日历权限失败");
                        }
                        openNewActivity(MainActivity.class);

                    }
                });
    }

    private void openNewActivity(Class<MainActivity> pClass) {
        Intent _Intent = new Intent();
        _Intent.setClass(this, pClass);
        startActivity(_Intent);
    }

    private View getContentView() {
        int rlTitleID = 1001;

        RelativeLayout contentView = new RelativeLayout(this);
        RelativeLayout.LayoutParams layoutLP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        contentView.setLayoutParams(layoutLP);
        contentView.setBackgroundResource(android.R.color.white);

        // 设置底部标题
        RelativeLayout rlTitle = new RelativeLayout(this);
//        rlTitle.setBackgroundColor(Color.parseColor("#008577"));
        rlTitle.setId(rlTitleID);

        RelativeLayout.LayoutParams titleLP = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                DensityUtil.dip2px(84));
//        RelativeLayout.LayoutParams titleTvLP = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT);

//        TextView tvTitle = new TextView(this);
//        tvTitle.setText(getString(R.string.app_name));
//        tvTitle.setTextColor(Color.parseColor("#ffffff"));
//        tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

//        titleTvLP.addRule(RelativeLayout.CENTER_IN_PARENT);
//        rlTitle.addView(tvTitle, titleTvLP);

        titleLP.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        if (isStartApp) {
            contentView.addView(rlTitle, titleLP);
        }

        // 展示广告的容器
        container = new FrameLayout(this);
        RelativeLayout.LayoutParams containerLP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        if (isStartApp) {
            containerLP.addRule(RelativeLayout.ABOVE, rlTitleID);
        }
        contentView.addView(container, containerLP);

        return contentView;
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<>();

        List<String> needCheckPermissions = getNeedCheckPermissions();
        for (String permission : needCheckPermissions) {
            if (!(checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED)) {
                lackedPermission.add(permission);
            }
        }

        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            fetchSplashAD(this, container, this);
        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限，如果获得权限就可以调用SDK，否则不要调用SDK。
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }

    private void fetchSplashAD(Activity activity, ViewGroup adContainer, SplashADListener adListener) {
        SplashAD splashAD = new SplashAD(activity, "51633", adListener);
        splashAD.show(adContainer);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024) {
            fetchSplashAD(this, container, this);
        }
    }

    /**
     * 处理跳转下个页面
     */
    public void next() {
        if (isStartApp) {
            if (mDisrupt) {
                startActivity(new Intent(this, MainActivity.class));
                finish();
            } else {
                mDisrupt = true;
            }
        } else {
            finish();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDisrupt) {
            next();
        }
        mDisrupt = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDisrupt = false;
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onFailed(ADError leError) {
        next();
    }

    @Override
    public void onADExposure() {

    }

    @Override
    public void onADClicked() {

    }

    @Override
    public void onADDismissed() {
        next();

    }

    @Override
    public void onADTick(long l) {

    }
}
